﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using Eshouse.Entity;
using System.Data;

namespace Eshouse.Bll
{
    public class dictItemAccess:IDisposable
    {
        protected ISession session { get; set; }
        public dictItemAccess()
        {
            NHibernateHelper Nhelper = new NHibernateHelper();
            session = Nhelper.GetSession();
        }
        //弹出修改对话框的html表格
        public static string GetMsgOnHtmlTb_Edit(string id)
        {
            string strSql =string.Format( "select  itemID,dictid,itemName from DicTable where itemID={0}",id);
           
            DatabaseHelper dbhelp=new DatabaseHelper();
            DataTable tab = dbhelp.ExecuteDataTable(strSql);
            if (tab.Rows.Count==0)
            {
              DataRow data = tab.NewRow();
                 data[0] = "";
                data[1] = "";
                data[2] = "";
                tab.Rows.Add(data);
            }
            DataRow chName = tab.NewRow();
            chName[0] = "";
            chName[1] = "所属类型";
            chName[2] = "项名称";
            tab.Rows.Add(chName);
            DataRow tap = tab.NewRow();
            tap[0] = "";
            tap[1] = (int)htmlUItableHelper.htmlTap.select;
            tap[2] = (int)htmlUItableHelper.htmlTap.txtBox;
            htmlUItableHelper.SelOpton = "select * from DicCode";
            tab.Rows.Add(tap);
            DataRow state = tab.NewRow();
            state[0] = "";
            state[1] = htmlUItableHelper.tapState.none;
            state[2] = htmlUItableHelper.tapState.none;
            tab.Rows.Add(state);
            DataRow tapNum =tab.NewRow();
            tapNum[0] = 1;
            tapNum[1] = 1;
            tapNum[2] = 1;
            tab.Rows.Add(tapNum);
            string res= htmlUItableHelper.CreateEditHtmlTable(tab);
            return res;

        }
        public bool Delete(int id)
        {
            bool seccess = true;            
            //如果采用":"+参数名方式使用参数，那么给参数赋值时不需要在参数名前加":"号，如query.SetInt32(":UserId", userId);就会报错  
            IQuery query = session.CreateSQLQuery("delete from DicTable where DicTable.itemID=:id");
            query.SetInt32("id", id);
            try
            {
                int affectedRows = query.ExecuteUpdate();
            }
            catch (Exception ex)
            {
                logRecord.RecordErr("删除字典项", ex);
                seccess = false;
            }           
            return seccess;
        }
        public static bool VerifyItems(DicTable dic,ref StringBuilder sb)
        {
            bool verify = true;
            if (dic.ItemName == "")
            {
                verify = false;
                sb.Append("项名称不能为空！");
            }
            else { 
              if(dic.ItemName.Length<2)
              {
                  verify = false;
                  sb.Append("项名称长度不能小于2！");
              }
            }
            if (VerifyItemName(dic.ItemName))
            {
                verify = false;
                sb.Append("该名称已经存在！");
            }
            if (dic.dictid.Id==0)
            {
                verify = false;
                sb.Append("请选择所属类型！");
            }
            return verify;
        }
        /// <summary>
        /// 验证字典名是否存在
        /// </summary>
        /// <param name="itemName"></param>
        /// <returns></returns>
        public static bool VerifyItemName(string itemName)
        {
            bool isexist = false;
            DatabaseHelper dbhelp = new DatabaseHelper();
            string strSql = "select itemID from DicTable where itemName='{0}'";
            object o = dbhelp.ExecuteScalar(string.Format(strSql, itemName.Trim()));
            if (o != null)
                isexist=true;
            return isexist;
        }
        /// <summary>
        /// 插入新的数据
        /// </summary>
        /// <param name="dicdt"></param>
        /// <returns></returns>
        public bool Insert(DicTable dicdt)
        {
            bool seccess = true;
            CRC32Primarykey crc=new CRC32Primarykey();
            DateTime now=DateTime.Now;
            int primaryKey=crc.createIntID("dictable"+ now.ToString("yyyyMMddhhmmss") + now.Millisecond.ToString());
            dicdt.Id = primaryKey;
            try {
                session.Save(dicdt);
                session.Flush();
            }
            catch(Exception ex)
            {
                logRecord.RecordErr("添加字典项",ex);
                seccess = false;
            }            
            return seccess; 
        }
        /// <summary>
        /// 更新数据
        /// </summary>
        /// <param name="dicdt"></param>
        /// <returns></returns>
        public bool Update(DicTable dicdt)
        {
            bool seccess = true;
            try {
                session.Update(dicdt);
                session.Flush();
            }
            catch(Exception ex)
            {
                logRecord.RecordErr("更新字典项", ex);
                seccess = false;
            }
            return seccess; 
        }
        /// <summary>
        /// json形式,配合 UI 分页控件使用
        /// </summary>
        /// <param name="pageIdx"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        public string GetListOnJson(int pageIdx, int size)
        {
            
            DataTable dt = GetDataTableList(pageIdx, size);
            int rowCount = GetItemCount();   
            
            return publicComm.GetJsonString(dt,rowCount);
        }
        /// <summary>
        /// 获取总数
        /// </summary>
        /// <returns></returns>
        public int GetItemCount()
        {
            string strSql = "select count(itemID) from DicTable";
            DatabaseHelper dbhelp = new DatabaseHelper();
            object o = dbhelp.ExecuteScalar(strSql);
            if (o == null)
                return 0;
            return Convert.ToInt32(o);
        }
        /// <summary>
        /// datatable形式
        /// </summary>
        /// <param name="pageIdx"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        public DataTable GetDataTableList(int pageIdx, int size)
        {
            DataTable dt = new DataTable();
            DataColumn col=new DataColumn("itemid");
            DataColumn col2=new DataColumn("catagrory");
            DataColumn col1=new DataColumn("itemname");
            dt.Columns.Add(col);
            dt.Columns.Add(col2);
            dt.Columns.Add(col1);

            IList<DicTable> list = GetList(pageIdx, size);
            DicTable tmpDic;
            for (int i = 0; i < list.Count;i++ )
            {
                DataRow row = dt.NewRow();
                tmpDic=list[i];
                row["itemid"] = tmpDic.Id;
                row["catagrory"] = tmpDic.dictid.DictName;
                row["itemname"] = tmpDic.ItemName;
                dt.Rows.Add(row);
            }
            return dt;
        }    
        /// <summary>
        /// 分页读取列表
        /// </summary>
        /// <param name="pageIdx"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        public IList<DicTable> GetList(int pageIdx,int size)
        {
            pageIdx=(pageIdx-1)*size;
            IList<DicTable> list;
            try {
                list = session.CreateCriteria(typeof(DicTable)).SetFirstResult(pageIdx).SetMaxResults(size).List<DicTable>();
            }
            catch(Exception ex)
            {
                logRecord.RecordErr("更新字典项", ex);
                list = null;
            }
            return list;
        }

        #region IDisposable 成员
        /// <summary>
        /// 清理关闭session
        /// </summary>
        public void Dispose()
        {
            //if (session.IsOpen)
            //session.Close();
        }

        #endregion
    }
}
